package java_util.coo_util;

import java_util.coo_util.Log.C_Log;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhouhe
 * @Date: 2019/6/19 8:48
 */
public class C_File {
    public static void test_main(String[] args) {
        // 文件夹路径
        String path = "D:\\input.txt";

        List<String> scanListPath = ReadAllLines(path);
//            System.out.println(scanListPath);
        assert scanListPath != null;
        for (String mytext : scanListPath) {
            //替换所有制表符
            mytext = mytext.replaceAll("\t", ",");
            System.out.println(mytext);
            //每一行都转化为新的数组，根据下标去判断参数值对应的参数是什么
            String[] strArr = mytext.split(","); //注意分隔符是需要转译
            for (int m = 0; m < strArr.length; m++) {
//                    System.out.println(strArr[m]);
                switch (m) {
                    case 0:
                        System.out.println("时间：" + strArr[m]);
                        break;
                    case 1:
                        System.out.println("甲烷：" + strArr[m]);
                        break;
                    case 2:
                        System.out.println("总烃：" + strArr[m]);
                        break;
                    case 3:
                        System.out.println("非甲烷总烃：" + strArr[m]);
                        break;
                    case 4:
                        System.out.println("氨气：" + strArr[m]);
                        break;
                    case 5:
                        System.out.println("硫化氢：" + strArr[m]);
                        break;
                    case 6:
                        System.out.println("氧气：" + strArr[m]);
                        break;
                    default:
                        break;
                }
            }
        }

    }


    public static void S_CareteDir(String dir) {
        File f = new File(dir);
        if (!f.exists()) {
            f.mkdirs(); //创建目录
        }
    }


    // 非递归
    public static List<String> S_scanFiles(String path) {
        List<String> filePaths = new ArrayList<String>();
        LinkedList<File> list = new LinkedList<File>();
        File dir = new File(path);
        File[] file = dir.listFiles();

        assert file != null;
        for (File value : file) {
            if (value.isDirectory()) {
                // 把第一层的目录，全部放入链表
                list.add(value);
            }
            filePaths.add(value.getAbsolutePath());
        }
        // 循环遍历链表
        while (!list.isEmpty()) {
            // 把链表的第一个记录删除
            File tmp = list.removeFirst();
            // 如果删除的目录是一个路径的话
            if (tmp.isDirectory()) {
                // 列出这个目录下的文件到数组中
                file = tmp.listFiles();
                if (file == null) {// 空目录
                    continue;
                }
                // 遍历文件数组
                for (File value : file) {
                    if (value.isDirectory()) {
                        // 如果遍历到的是目录，则将继续被加入链表
                        list.add(value);
                    }
                    filePaths.add(value.getAbsolutePath());
                }
            }
        }
        return filePaths;
    }

    //打印文件夹下所有的子文件夹
    public void getList(String patha) {
        String path = patha;
        File file = new File(path);
        File[] tempList = file.listFiles();
        System.out.println("该目录下对象个数：" + tempList.length);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {

                System.out.println("文     件：" + tempList[i]);
            }
            if (tempList[i].isDirectory()) {
                System.out.println("文件夹：" + tempList[i].getPath());

                //递归：
                getList(tempList[i].getPath());
            }
        }
    }

    //读取一个文本 一行一行读取
    public static List<String> ReadAllLines(String path) {
        List<String> list = new ArrayList<String>();
        try {
            File file = new File(path);
            if (!file.exists()) {
                C_Log.LogError("文件不存在..无法读取....." + path);
                return null;
            }
            // 使用一个字符串集合来存储文本中的路径 ，也可用String []数组

            FileInputStream fis = new FileInputStream(path);
            // 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8，在电脑上自己创建的txt  用GBK
            InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null) {
                // 如果 t x t文件里的路径 不包含---字符串       这里是对里面的内容进行一个筛选
                //if (line.lastIndexOf("---") < 0) {
                list.add(line);
                //}
            }
            br.close();
            isr.close();
            fis.close();
        } catch (Exception ex) {
            C_Log.LogErrorInfo("文件不存在..无法读取....." + path, ex, true);
            return null;
        }
        return list;
    }

    public static String ReadAllTxt(String fullPath) {
        StringBuffer ssb = new StringBuffer();
        try {
            FileReader reader = new FileReader(fullPath);
            BufferedReader br = new BufferedReader(reader);
            String line;
//            while ((line = br.readLine()) != null) {
//                System.out.println(line);
//            }
            while ((line = br.readLine()) != null) {
                ssb.append(line);
            }
            br.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ssb.toString();
    }

    //拷贝文件
    public static void S_fileCopy(String sourcePath, String targetPath) {
        C_Log.LogFormat("S_fileCopy.....%s........%s", sourcePath, targetPath);
        int n = 0;
        try {
            FileInputStream source = new FileInputStream(sourcePath);
            FileOutputStream target = new FileOutputStream(targetPath);
            while ((n = source.read()) != -1) {
                target.write(n);
            }
            source.close();
            target.close();
        } catch (FileNotFoundException e) {
            C_Log.LogException("S_fileCopy.1.错误...", e);
            // e.printStackTrace();
        } catch (IOException e) {
            C_Log.LogException("S_fileCopy.2.错误...", e);
            //e.printStackTrace();
        }
    }

    /**
     * 删除空目录
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    public static boolean S_delete(String dir) {
        C_Log.LogFormat("删除路径......%s", dir);
        boolean bb = S_delete(new File(dir));
        C_Log.LogFormat("删除路径..完成....%s", dir);
        if (bb) {
            C_Log.LogFormat("删除失败...........%s", dir);
        }
        return bb;
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     */
    public static boolean S_delete(File dir) {
        if (!dir.exists()) {
            C_Log.LogFormat("目录不存在.......%s", dir.getPath());
            return false;
        }
        if (dir.isFile()) {
            C_Log.LogFormat("删除文件........%s", dir.getPath());
            return dir.delete();
        } else if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            assert children != null;
            for (String child : children) {
                String path = dir.getPath() + "\\" + child;
                boolean success = S_delete(new File(path));
                if (!success) {
                    C_Log.LogFormat("删除失败.......%s", path);
                    // return false;
                }
            }
        }
        //目录此时为空，可以删除
        return dir.delete();
    }

    //保存文件
    public static void S_Save(String savePath, String data) {
        S_Save(savePath, C_Bytes.S_StringToBytes(data));
    }

    //保存文件
    public static void S_Save(String savePath, byte[] data) {
        try {
            FileOutputStream target = new FileOutputStream(savePath);
            target.write(data);
            target.close();
        } catch (FileNotFoundException e) {
            C_Log.LogErrorFormat("S_Save.1.错误....%s........%s", e.getMessage(), e.fillInStackTrace());
            e.printStackTrace();
        } catch (IOException e) {
            C_Log.LogErrorFormat("S_Save.2.错误....%s........%s", e.getMessage(), e.fillInStackTrace());
            e.printStackTrace();
        }
    }


    public static boolean S_copyDir(String oldPath, String newPath) {
        C_Log.LogFormat("拷贝目录.....%s........%s", oldPath, newPath);
        boolean result = true;
        String[] filePaths = new File(oldPath).list();

        if (filePaths != null && filePaths.length > 0) {
            if (!new File(newPath).exists()) {
                if (!new File(newPath).mkdirs()) {
                    C_Log.error("文件夹创建失败");
                    return false;
                }
            }
            try {
                for (String filePath : filePaths) {
                    if (new File(oldPath + File.separator + filePath).isDirectory()) {
                        S_copyDir(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                    } else if (new File(oldPath + File.separator + filePath).isFile()) {
                        //复制文件到另一个目录
                        S_copyFile(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                        //移动文件至另一个目录
//                        String path0 = oldPath + File.separator + filePath;
//                        String path1 = newPath + File.separator + filePath;
//                        if (!new File(path0).renameTo(new File(path1))) {
//                            System.out.println(oldPath + File.separator + filePath + "文件复制失败");
//                            result = false;
//                            //break;
//                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void S_copyFile(String oldPath, String newPath) throws IOException {
        C_Log.LogFormat("拷贝文件.....%s........%s", oldPath, newPath);
        File oldFile = new File(oldPath);
        if (!oldFile.exists()) {
            C_Log.LogErrorFormat("拷贝文件.失败......文件不存在......%s....", oldPath);
            return;
        }
        try {
            File file = new File(newPath);
            FileInputStream in = new FileInputStream(oldFile);
            try {
                FileOutputStream out = new FileOutputStream(file);
                byte[] buffer = new byte[2097152];
                int len = 10;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.flush();
                in.close();
                out.close();
            } catch (Exception ex) {
                in.close();
                C_Log.LogErrorInfo("拷贝文件.失败....文件错误..", ex, true);
            }
        } catch (Exception ex) {
            C_Log.LogErrorInfo("拷贝文件.失败222....文件错误..", ex, true);
        }
    }

    /**
     * 拷贝文件夹并-替换文本文件中的字符串
     *
     * @param oldPath
     * @throws IOException
     */
    public static boolean S_moveDir_ReplacTextContent(String oldPath, String newPath, String srcStr0, String replaceStr0) {
        boolean result = true;
        String[] filePaths = new File(oldPath).list();

        if (filePaths != null && filePaths.length > 0) {
            if (!new File(newPath).exists()) {
                if (!new File(newPath).mkdirs()) {
                    System.out.println("文件夹创建失败");
                    return false;
                }
            }

            try {
                for (String filePath : filePaths) {
                    if (new File(oldPath + File.separator + filePath).isDirectory()) {
                        S_moveDir_ReplacTextContent(oldPath + File.separator + filePath, newPath + File.separator + filePath, srcStr0, replaceStr0);
                    } else if (new File(oldPath + File.separator + filePath).isFile()) {
                        //复制文件到另一个目录
                        S_copyFile_ReplacTextContent(oldPath + File.separator + filePath, newPath + File.separator + filePath, srcStr0, replaceStr0);
                        //移动文件至另一个目录
//                        if(!new File(oldPath + File.separator + filePath).renameTo(new File(newPath + File.separator + filePath))){
//                            System.out.println(oldPath + File.separator + filePath +"文件复制失败");
//                            result = false;
//                            break;
//                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 拷贝并-替换文本文件中的字符串
     *
     * @param oldPath
     * @throws IOException
     */
    public static void S_copyFile_ReplacTextContent(String oldPath, String targetPath, String srcStr0, String replaceStr0) throws IOException {
        // 读
        //File file = new File(path);
        //FileReader in = new FileReader(file);
        BufferedReader bufIn = new BufferedReader(new FileReader(new File(oldPath)));
        // 内存流, 作为临时流
        CharArrayWriter tempStream = new CharArrayWriter();
        // 替换
        String line = null;
        while ((line = bufIn.readLine()) != null) {
            if (srcStr0 != null) {
                // 替换每行中, 符合条件的字符串
                line = line.replaceAll(srcStr0, replaceStr0);
            }
            // 将该行写入内存
            tempStream.write(line);
            // 添加换行符
            tempStream.append(System.getProperty("line.separator"));
        }
        // 关闭 输入流
        bufIn.close();
        // 将内存中的流 写入 文件
        FileWriter out = new FileWriter(new File(targetPath));
        tempStream.writeTo(out);
        out.close();
        System.out.println("====path:" + oldPath);
    }


}